#!/usr/python3.6.3/bin/python3
# -*- coding: utf-8 -*-
import subprocess
import requests
import sys


class Ts:
    """
    检测工具类
    """

    @staticmethod
    def testurl(url):
        """
        test url is return 200
        :return: utl响应码 or False
        """
        try:
            r = requests.get(url, timeout=5)
            print(url, end='')
            print('    .........   ', end='')
            print(r.status_code)
            return r.status_code
        except:
            print('服务五秒内没有响应,-_-!')
            return False

    @staticmethod
    def errorlist(stderrs, project, info):
        if stderrs:
            print("出错了!!!")
            print(stderrs)
            print('''
                 自动更新脚本出错了，我已发邮件通知运维了，
                 防止运维没有及时看到,请电话通知运维。''')
            subprocess.call('/sh/emaills.py {} {}'.format(project, info),
                            shell=True)


class BaseSvn:
    """
    svn 更新类
    """
    def upd_svn(self):
        req = subprocess.Popen(
            'svn co svn://****:**/project/Release/ /usr/Release/',
            shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
        )
        # 不想输出svn拉取代码的详细信息，使用Popen
        (stdeout, stderrs) = req.communicate()
        Ts.errorlist(stderrs, 'svnerr', 'svnerr')
        # 打印svn版本号
        print(stdeout.decode('utf-8').split('\n')[-2])


class TsMerweb(BaseSvn):
    """
    商户后台更新类
    """
    project = '测试环境-商户后台'
    info = '更新失败'

    def upd_code(self):
        # svn update
        super().upd_svn()
        # 代码同步
        req = subprocess.call(
            'rsync  -avzrP --exclude "*.svn" --delete  /usr/Release/**path**/ /**tomcatPath**/ROOT/',
            shell=True)
        Ts.errorlist(req, TsMerweb.project, TsMerweb.info)
        # kill tomcat
        if not subprocess.call(
                'ps -ef | grep "/**tomcatPath**/" | grep -v "/bin/sh -c ps x" | grep -v "grep"',
                shell=True):
            req = subprocess.call(
                '''ps -ef | grep "/**tomcatPath**/" | grep -v "/bin/sh -c ps x" | grep -v "grep" | awk '{print $2}' | xargs kill -9 ''',
                shell=True)

        # 启动
        req = subprocess.Popen(
            'ssh root@127.0.0.1 -p** "/**tomcatPath**/bin/startup.sh"', shell=True)
        (stdeout, stderrs) = req.communicate()
        Ts.errorlist(stderrs, TsMerweb.project, TsMerweb.info)
        
        # 操作完毕，信息打印
        subprocess.call(
                'ps -ef | grep "/**tomcatPath**/" | grep -v "/bin/sh -c ps x" | grep -v "grep"',
                shell=True)
        Ts.testurl('http://***.com')
        

class TsBacksys(BaseSvn):
    """
    系统后台更新类
    """
    project = '测试环境-系统后台'
    info = '更新失败'

    def upd_code(self):
        # svn update
        super().upd_svn()
        # 代码同步
        req = subprocess.call(
            'rsync  -avzrP --exclude "*.svn" --delete  /usr/Release/**path**/ /**tomcatPath**/ROOT/',
            shell=True)
        Ts.errorlist(req, TsBacksys.project, TsBacksys.info)
        # kill tomcat
        if not subprocess.call(
                'ps -ef | grep "/**tomcatPath**/" | grep -v "/bin/sh -c ps x" | grep -v "grep"',
                shell=True):
            req = subprocess.call(
                '''ps -ef | grep "/**tomcatPath**/" | grep -v "/bin/sh -c ps x" | grep -v "grep" |awk '{print $2}'| xargs kill -9''',
                shell=True)

        # 启动
        req = subprocess.Popen(
            'ssh root@127.0.0.1 -p*** "/**tomcatPath**/bin/startup.sh"',
            shell=True)
        (stdeout, stderrs) = req.communicate()
        Ts.errorlist(stderrs, TsBacksys.project, TsBacksys.info)

        # 操作完毕，信息打印
        subprocess.call(
            'ps -ef | grep "/**tomcatPath**/" | grep -v "/bin/sh -c ps x" | grep -v "grep"',
            shell=True)
        Ts.testurl('http://****.com')


class OrderFrom(BaseSvn):
    """
    电商生成虚拟订单数据，更新类
    """
    project = '虚拟外购订单'
    info = '更新失败'

    def upd_code(self):
        # svn update
        super().upd_svn()
        # 同步代码
        req = subprocess.call(
            'rsync  -avzrP --exclude "*.svn" --delete  /usr/Release/**path**/ /**tomcatPath**/ROOT/',
            shell=True)
        Ts.errorlist(req, OrderFrom.project, OrderFrom.info)

        # kill tomcat
        if not subprocess.call(
                'ps -ef | grep "/**tomcatPath**/" | grep -v "/bin/sh -c ps x" | grep -v "grep"',
                shell=True):
            req = subprocess.call(
                '''ps -ef | grep "/**tomcatPath**/" | grep -v "/bin/sh -c ps" | grep -v "grep" | awk '{print $2}' | xargs kill -9  ''',
                shell=True)
        # 启动
        req = subprocess.Popen(
            ''' ssh root@127.0.0.1 -p*** "/**tomcatPath**/bin/startup.sh" ''',
            shell=True)
        (stdeout, stderrs) = req.communicate()
        Ts.errorlist(stderrs, OrderFrom.project, OrderFrom.info)
        # 检测
        subprocess.call(
                'ps -ef | grep "**tomcatPath**" | grep -v "/bin/sh -c ps x" | grep -v "grep"',
                shell=True)
        Ts.testurl('http://*****.com')

        
class SetUpdate:
    def set_values(self, values):
        self.values = values()

    def upd_code(self):
        self.values.upd_code()


if __name__ == '__main__':
    update = SetUpdate()
    
    if sys.argv[1] == 'TS':
        if sys.argv[2] == 'Merweb':
            update.set_values(TsMerweb)
            update.upd_code()

        if sys.argv[2] == 'Backsys':
            update.set_values(TsBacksys)
            update.upd_code()

        if sys.argv[2] == 'OrderFrom':
            update.set_values(OrderFrom)
            update.upd_code()

